package com.blog.auth.config;

import com.blog.auth.dao.AuthMenuDao;
import com.blog.auth.dao.AuthPermissionDao;
import com.blog.auth.dao.AuthUserDao;
import com.blog.auth.pojo.AuthMenu;
import com.blog.auth.pojo.AuthUser;
import com.blog.auth.pojo.SecurityUser;
import com.blog.auth.service.AuthMenuService;
import com.blog.auth.util.UserJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/*****
 * 自定义授权认证类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    AuthUserDao authUserDao;

    @Autowired
    AuthMenuDao authMenuDao;

    @Autowired
    AuthMenuService authMenuService;

    /****
     * 自定义授权认证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //===================客户端信息认证 start===================
        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if(authentication==null){
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if(clientDetails!=null){
                //密码
                String clientSecret = clientDetails.getClientSecret();
                return new User(username,clientSecret,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }
        //===================客户端信息认证 end===================

        //===================用户账号密码信息认证 start===================
        if (StringUtils.isEmpty(username)) {
            return null;
        }

        //根据用户名查询用户信息
        AuthUser user = authUserDao.getUserByUsername(username);
        if (user == null) {
            // 如果用户查询不到，返回provier来抛异常
            return null;
        }
//        String pwd = new BCryptPasswordEncoder().encode("szitheima");
        String password = user.getPassword();
        //创建User对象
        //String permissions = "user";
        StringBuffer permissions = new StringBuffer();

        // 根据用户的id查询用户的权限
        String userId = user.getId();
        List<AuthMenu> permissionList = authMenuService.selectPermissionUserId(userId);

        List<String> menuList = new ArrayList<String>();
        for (AuthMenu authMenu : permissionList) {
            String menuName = authMenu.getMenuName();
            menuList.add(menuName);
            permissions.append(menuName);
            permissions.append(",");
        }
        SecurityUser securityUser = new SecurityUser();
        securityUser.setPermissionValueList(menuList);
        //===================用户账号密码信息认证 end===================
        //userDetails.setComy(songsi);
        UserJwt userDetails = new UserJwt(username,password,AuthorityUtils.commaSeparatedStringToAuthorityList(permissions.toString()));
        return userDetails;
    }
}
